#ifndef CSVMANAGER_H
#define CSVMANAGER_H

#include <QObject>
#include <QTextCodec>
#include "sm-global.h"

class QModelIndex;
typedef QList<QModelIndex> QModelIndexList;
class QAbstractItemModel;
class QTableView;
class QxtCsvModelEx;

class CsvManager : public QObject
{
    Q_OBJECT
public:
    explicit CsvManager (QObject *parent = 0);

    enum ExportState { InvalidState, NothingToExport, CannotExportToFile, ExportSuccessful };
    ExportState state() const;
    QString path() const;
    QString filePath() const;

public slots:
    bool exportToCsv (const QTableView* tableView, const QString& fileName,
                      const SmGlobal::CellsRange cellsRange = SmGlobal::AllCells,
                      const SmGlobal::ColumnsVisibility columnsVisibility = SmGlobal::VisibleColumns,
                      const bool withHeader = false, bool forceNumbersFormat = true, const QChar& separator = ',',
                      QTextCodec* codec = QTextCodec::codecForName("System"));
    QxtCsvModelEx* importFromCsv (const QString& fileName, bool withHeader = false, const QChar& separator = ',',
                                  QTextCodec* codec = QTextCodec::codecForName("System"));

private:
    void setModelHeaderData (QxtCsvModelEx& csvModel, const SmGlobal::ColumnsVisibility columnsVisibility,
                             const bool withHeader, QAbstractItemModel* model);
    void setModelData (QxtCsvModelEx& csvModel, const QModelIndexList& indexes);
    void setState (ExportState state);
    QModelIndexList findIndexes (const SmGlobal::CellsRange cellsRange,
                                 const SmGlobal::ColumnsVisibility columnsVisibility);
    int findRowCount (const QModelIndexList& indexes, int columnCount = -1);
    int findColumnCount (const QModelIndexList& indexes);
    QStringList findHeaderData (const SmGlobal::ColumnsVisibility columnsVisibility);
    QList<QStringList> findHeaderData (QAbstractItemModel* headerModel,
                                       const SmGlobal::ColumnsVisibility columnsVisibility);
    QList<QStringList> findMultipleSectionData (const QModelIndex& item, QAbstractItemModel* headerModel,
                                                const SmGlobal::ColumnsVisibility columnsVisibility);
    void findMultipleSectionData (const QModelIndex& item, const int section, const int level,
                                  QList<QStringList>& headerDataList, QAbstractItemModel* headerModel);
    void findMultipleSectionVisibleData (const QModelIndex &item, const int position, const int level,
                                         QList<QStringList> &headerDataList, QAbstractItemModel *headerModel);
    QStringList createEmptyRow (const int size);
    void resizeRows (const int newSize, QList<QStringList>& dataList);
    void resizeRow (const int newSize, const int row, QList<QStringList>& dataList);

    const QTableView* m_tableView;
    ExportState m_state;
    QString m_filePath;
};

#endif // CSVMANAGER_H
